package cn.zhqr.core.service;

import cn.zhqr.common.bean.response.ErrorCode;
import cn.zhqr.common.bean.response.OutResponse;
import cn.zhqr.common.config.GlobalConstants;
import cn.zhqr.common.util.collections.CollectionUtils;
import cn.zhqr.db.model.OrderSplitRule;
import cn.zhqr.db.model.Station;
import org.apache.log4j.Logger;

import java.math.BigDecimal;
import java.util.List;

/**
 * 订单分账规则
 */
public class OrderSplitRuleService {
    public static final OrderSplitRuleService instance = new OrderSplitRuleService();
    private static final Logger logger = Logger.getLogger(OrderSplitRuleService.class);


    /**
     * 获取订单分账规则
     * @param stationId
     * @return
     */
    public List<OrderSplitRule> getOrderSplitRules(Long stationId) {
        List<OrderSplitRule> splitList = OrderSplitRule.dao.findByStationId(stationId);
        if(CollectionUtils.isEmpty(splitList)){
            Station station = Station.dao.findById(stationId);
            if(station != null){
                OrderSplitRule orderSplitRule = new OrderSplitRule();
                orderSplitRule.setAgentId(station.getOwnerId());
                orderSplitRule.setStationId(station.getId());
                orderSplitRule.setPercent(GlobalConstants.HUNDRED);
                splitList.add(orderSplitRule) ;
            }
        }
        return splitList;
    }

    public OutResponse checkSplitRules(List<OrderSplitRule> orderSplitRules){
        BigDecimal totalPercent = BigDecimal.ZERO;
        for(OrderSplitRule rule : orderSplitRules){
            totalPercent = totalPercent.add(rule.getPercent()!=null?rule.getPercent():BigDecimal.ZERO);
        }
        if(totalPercent.compareTo(GlobalConstants.HUNDRED)!=0){
           return OutResponse.buildError(ErrorCode.INVALID_PARAM,"分账比例总和不等于100%");
        }

        return OutResponse.buildSuccess();
    }
}
